package com.xiaomaoguai.fcp.pre.kepler.router.utils;

import java.net.InetAddress;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

import org.apache.commons.lang3.time.FastDateFormat;

public class GenPipeNumber {

	private static final FastDateFormat pattern = FastDateFormat.getInstance("yyyyMMddHHmmss");

	private final static AtomicInteger value = new AtomicInteger(100000);
	private static String num;
	static {

		try {
			num = InetAddress.getLocalHost().getHostAddress().split("\\.")[3];
		} catch (Exception e) {
			num = String.valueOf(new Random().nextInt(9));
		}
	}

	public static int incrementAndGet() {
		for (;;) {
			int current = get();
			int next = current == 999999 ? 100000 : current + 1;
			if (compareAndSet(current, next))
				return next;
		}
	}

	public static int get() {
		return value.get();
	}

	public static boolean compareAndSet(final int current, final int next) {
		if (value.compareAndSet(current, next)) {
			return true;
		} else {
			LockSupport.parkNanos(1L);
			return false;
		}
	}

	/**
	 * 获取序列数
	 * 
	 * @return
	 */
	public static String getSerialNum() {
		return pattern.format(System.currentTimeMillis()) + num + incrementAndGet();
	}

	public static void main(String[] args) {
		ExecutorService pool = Executors.newFixedThreadPool(500);
		final AtomicInteger num = new AtomicInteger(0);
		while (true) {
			pool.execute(() -> {
				System.out.println(num.incrementAndGet()+"|"+getSerialNum());
			});
		}
	}

}
